package diycode

import (
	"fmt"
	"strconv"
)

// 16进制字符串
type HexKey struct {
	List       []string
	OrderSlice CodeSlice
}

// 通过指定的有序的字符项数组
// 令乱序的字符项数组生成16进制字符串
func (c CodeSlice) GenHexKeyFromOrderSlice(orderSlice *CodeSlice) (*HexKey, error) {
	res := HexKey{
		List:       []string{},
		OrderSlice: *orderSlice,
	}
	for _, item := range c {
		target, err := orderSlice.FindChar(item.Char)
		if err != nil {
			return nil, err
		}
		key := fmt.Sprintf("%02X", target.Index)
		res.List = append(res.List, key)

	}

	return &res, nil
}

// 通过指定的有序的字符项数组
//
// 默认指定为 diycode.CodeStr
//
// 令乱序的字符项数组生成16进制字符串
func (c CodeSlice) GenHexKey() (*HexKey, error) {
	codeSlice := GetCodeSliceFromStr(CodeStr)
	return c.GenHexKeyFromOrderSlice(&codeSlice)
}

func (h *HexKey) PrintStringText() string {
	var str string
	for i, key := range h.List {
		var adder string
		if i == 0 {
			adder = key
		} else {
			adder = " " + key
		}

		str += adder

	}

	return str
}

func (h *HexKey) ParseToCodeSlice() (CodeSlice, error) {
	res := make(CodeSlice, len(h.List))
	for i, item := range h.List {
		num, err := strconv.ParseInt(item, 16, 32)
		if err != nil {
			return nil, err
		}

		target, err := h.OrderSlice.FindIndex(int(num))
		if err != nil {
			return nil, err
		}

		res[i] = *target
	}

	return res, nil
}

// 反解原始字符串
func (h *HexKey) ParseOriginText() (string, error) {
	var res string
	for _, item := range h.List {
		num, err := strconv.ParseInt(item, 16, 32)
		if err != nil {
			return "", err
		}

		target, err := h.OrderSlice.FindIndex(int(num))
		if err != nil {
			return "", err
		}

		res += target.Char
	}

	return res, nil
}
